package com.example.demo.user.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.user.entity.TUser;
import com.example.demo.user.service.ITUserService;
import com.example.demo.utils.ZUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;
import com.example.demo.base.BaseController;
import org.springframework.web.client.RestTemplate;

import java.sql.Wrapper;
import java.util.Map;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author zhongz
 * @since 2019-02-16
 */
@RestController
@RequestMapping("/user/t-user")
public class TUserController extends BaseController {

    final String APPID = "wx52140f7496462066";

    final String SECRET = "421b7ba441424d11d009dab88b3af479";

    @Autowired
    private ITUserService userService;

    @GetMapping("/openid/{code}")
    @SuppressWarnings("unchecked")
    public Map<String, Object> getUid(@PathVariable String code) {
        String uri = "https://api.weixin.qq.com/sns/jscode2session?appid=" + APPID + "&secret=" + SECRET + "&js_code="
                + code + "&grant_type=authorization_code";
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<String> entity = new HttpEntity<String>(headers);
        String strbody = restTemplate.exchange(uri, HttpMethod.GET, entity, String.class).getBody();
        Map<String, Object> map = (Map<String, Object>) JSONObject.parse(strbody);
        String openid = map.get("openid").toString();
        TUser user = this.getByOpenid(openid);
        if (user == null) {
            // 新建
            user = new TUser();
            user.setId(ZUtils.getUUID());
            user.setOpenId(openid);
            userService.save(user);
        }
        return success(user);
    }

    private TUser getByOpenid(String openid) {
        QueryWrapper<TUser> wrapper = new QueryWrapper<>();
        wrapper.eq("OPEN_ID", openid);
        return userService.getOne(wrapper);
    }
}
